import random
from flask import render_template, make_response, Blueprint, request
from flask_mail import Message, Mail
from query.admin_query import find_one_admin
from query.mail_query import add_one_mail, find_one_mail, update_one_mail
from utils.index import request_get, return_format
from utils.utils import return_model


mail = Blueprint('sendMail', __name__)

Mail = Mail()


@mail.route('/send_code', methods=['POST'])
def send_code():
    email = request_get("mail")
    start_time = request_get("start_time")
    # 生成一个6位的密码
    code = ""
    for i in range(6):
        code += str(random.randint(0, 9))

    subject = '你的邮箱验证码：'  # 标题
    recipients = [email]  # 接收人的邮箱
    sender = 'qmcovo@qq.com'  # 发送人的邮箱

    find_one_admin_data = find_one_admin({"mail": email})
    # if find_one_admin_data is None:
    # 首先判断查询admin中是否有当前邮箱号，如果查询成功则执行查询成功的逻辑，如果查询不成功则返回查询失败
    if find_one_admin_data["msg"] == "success":
        # 判断admin是否有当前邮箱，如果有则返回当前邮箱已注册，如果没有则执行发送邮件的逻辑
        if find_one_admin_data["data"] is None:
            find_one_mail_data = find_one_mail({"mail": email})
            # 判断mail是否查询成功
            if find_one_mail_data["msg"] == "success":
                # 如果为none则证明mail表中不存在当前邮箱，则执行添加操作
                # 如果不为none则证明当前mail表中已经有此邮箱了，则执行更新操作
                if find_one_mail_data["data"] is None:
                    add_one_mail_data = add_one_mail({
                        "mail": email,
                        "code": code,
                        "start_time": start_time
                    })
                    msg = Message(subject=subject, sender=sender, recipients=recipients)
                    msg.html = render_template("mail.html", to_mail=code)
                    Mail.send(msg)
                    title = "验证码发送成功,请及时在邮箱查看,如果未收到邮件请查看邮箱地址是否正确或及时与我联系!"
                    return make_response((
                        return_format(title, return_model(add_one_mail_data["data"].mail_to_dict(), ["mail"]), 200)))
                elif find_one_mail_data["data"] is not None:
                    update_one_mail_data = update_one_mail({
                        "mail": email,
                    }, {"code": code,
                        "start_time": start_time})
                    mail_data = update_one_mail_data["data"].mail_to_dict()
                    msg = Message(subject=subject, sender=sender, recipients=recipients)
                    msg.html = render_template("mail.html", to_mail=code)
                    Mail.send(msg)
                    title = "验证码发送成功,请及时在邮箱查看,如果未收到邮件请查看邮箱地址是否正确或及时与我联系!"
                    return make_response((
                        return_format(title, return_model(mail_data, ["mail"]), 200)))
            elif find_one_mail_data["msg"] == "error":
                return make_response((return_format("查询失败!", None, 500)))
        elif find_one_admin_data["data"] is not None:
            return make_response((return_format("此邮箱已被注册!", None, 204)))
    elif find_one_admin_data["msg"] == "error":
        return make_response((return_format("查询失败!", None, 500)))


@mail.route('/proving_code', methods=['POST'])
def proving_code():
    email = request_get("mail")
    code = request_get("code")
    current_time = request_get("current_time")
    find_one_mail_data = find_one_mail({"mail": email})
    if find_one_mail_data["msg"] == "success":
        # 判断当前邮箱是否存在如果不存在那么就提醒用户当前邮箱并不存在
        # 如果存在则判断验证码是否正确，验证码是否过期等等
        if find_one_mail_data["data"] is None:
            return make_response((return_format("当前邮箱并不存在,请重新检查邮箱是否正确!", None, 204)))
        elif find_one_mail_data["data"] is not None:
            mail_data = find_one_mail_data["data"].mail_to_dict()
            # 现在的时间
            current_time = int(current_time)
            # 发送邮件的时间
            start_time = int(mail_data["start_time"])
            # 时间差
            diff_time = current_time - start_time
            # 如果用户的code与数据库的code相同和现在时间减去发送时间小于一个小时
            if code == mail_data["code"] and diff_time <= 1000 * 60 * 60:
                return make_response((return_format(None, None, 200)))
            elif code != mail_data["code"]:
                return make_response((return_format("验证码错误!", None, 204)))
            elif diff_time > 1000 * 60 * 60:
                return make_response((return_format("验证码已过期，请重新发送!", None, 204)))
    elif find_one_mail_data["msg"] == "error":
        return make_response((return_format("验证码查询失败!", None, 500)))


def init_app(app):
    Mail.init_app(app)
